/*
 * Copyright (c) 2009-2010 HIT Microelectronic Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * Authors: Gou Pengfei
 *          Jin Yinghan
 *
 * Date: Dec. 2009
 *
 */

#ifndef __CPU_EDGE_MAP_HH__
#define __CPU_EDGE_MAP_HH__

#include <queue>

#include "base/statistics.hh"
#include "base/timebuf.hh"

class DerivEdgeCPUParams;

template<class Impl>
class SimpleEdgeMap
{
  private:
    // Typedefs from the Impl.
    typedef typename Impl::CPU CPU;
    typedef typename Impl::DynInstPtr DynInstPtr;
    typedef typename Impl::EdgeBlockPtr BlockPtr;

    typedef typename Impl::CPUPol CPUPol;

    typedef TheISA::BlockID BlockID;

    // Typedefs from the CPU policy.
    typedef typename CPUPol::Fetch2Map Fetch2Map;
    typedef typename CPUPol::Map2Execute Map2Execute;
    typedef typename CPUPol::TimeStruct TimeStruct;

  public:
    /** Overall map stage status. Used to determine if the CPU can
     * deschedule itself due to a lack of activity.
     */
    enum MapStatus {
        Active,
        Inactive
    };

    /** Individual thread status. */
    enum ThreadStatus {
        Running,
        Idle,
        StartSquash,
        Squashing,
        Blocked,
        Unblocking
    };

  private:
    /** Map status. */
    MapStatus _status;

    /** Per-thread status. */
    ThreadStatus mapStatus[Impl::MaxThreads];

  public:
    /** SimpleEdgeMap constructor. */
    SimpleEdgeMap(CPU *_cpu, DerivEdgeCPUParams *params);

    /** Returns the name of map. */
    std::string name() const;

    /** Registers statistics. */
    void regStats();

    /** Sets the main backwards communication time buffer pointer. */
    void setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr);

    /** Sets pointer to time buffer used to communicate to the next stage. */
    void setMapQueue(TimeBuffer<Map2Execute> *dq_ptr);

    /** Sets pointer to time buffer coming from fetch. */
    void setFetchQueue(TimeBuffer<Fetch2Map> *fq_ptr);

    /** Sets pointer to list of active threads. */
    void setActiveThreads(std::list<ThreadID> *at_ptr);

    /** Drains the map stage. */
    bool drain();

    /** Resumes execution after a drain. */
    void resume() { }

    /** Switches out the map stage. */
    void switchOut() { }

    /** Takes over from another CPU's thread. */
    void takeOverFrom();

    /** Ticks map, processing all input signals and decoding as many
     * instructions as possible.
     */
    void tick();

    /** Determines what to do based on map's current status.
     * @param status_change map() sets this variable if there was a status
     * change (ie switching from from blocking to unblocking).
     * @param tid Thread id to map instructions from.
     */
    void map(bool &status_change, ThreadID tid);

    /** Processes instructions from fetch and passes them on to rename.
     * Decoding of instructions actually happens when they are created in
     * fetch, so this function mostly checks if PC-relative branches are
     * correct.
     */
    void mapInsts(ThreadID tid);

  private:
    /** Inserts a thread's instructions into the skid buffer, to be mapd
     * once map unblocks.
     */
    void skidInsert(ThreadID tid);

    /** Returns if all of the skid buffers are empty. */
    bool skidsEmpty();

    /** Updates overall map status based on all of the threads' statuses. */
    void updateStatus();

    /** Separates instructions from fetch into individual lists of instructions
     * sorted by thread.
     */
    void sortInstBlocks();

    /** Reads all stall signals from the backwards communication timebuffer. */
    void readStallSignals(ThreadID tid);

    /** Checks all input signals and updates map's status appropriately. */
    bool checkSignalsAndUpdate(ThreadID tid);

    /** Checks all stall signals, and returns if any are true. */
    bool checkStall(ThreadID tid) const;

    /** Returns if there any instructions from fetch on this cycle. */
    inline bool fetchInstsValid();

    /** Switches map to blocking, and signals back that map has
     * become blocked.
     * @return Returns true if there is a status change.
     */
    bool block(ThreadID tid);

    /** Switches map to unblocking if the skid buffer is empty, and
     * signals back that map has unblocked.
     * @return Returns true if there is a status change.
     */
    bool unblock(ThreadID tid);

    /** Squashes if there is a PC-relative branch that was predicted
     * incorrectly. Sends squash information back to fetch.
     */
    //void squash(DynInstPtr &inst, ThreadID tid);
     void squash(BlockPtr &inst_block, ThreadID tid);

  public:
    /** Squashes due to commit signalling a squash. Changes status to
     * squashing and clears block/unblock signals as needed.
     */
    unsigned squash(ThreadID tid);

  private:
    // Interfaces to objects outside of map.
    /** CPU interface. */
    CPU *cpu;

    /** Time buffer interface. */
    TimeBuffer<TimeStruct> *timeBuffer;

    /** Wire to get execute's output from backwards time buffer. */
    typename TimeBuffer<TimeStruct>::wire fromExecute;

    /** Wire to get commit's information from backwards time buffer. */
    typename TimeBuffer<TimeStruct>::wire fromCommit;

    /** Wire to write information heading to previous stages. */
    // Might not be the best name as not only fetch will read it.
    typename TimeBuffer<TimeStruct>::wire toFetch;

    /** Map instruction queue. */
    TimeBuffer<Map2Execute> *map2executeQueue;

    /** Wire used to write any information heading to rename. */
    typename TimeBuffer<Map2Execute>::wire toExecute;

    /** Fetch instruction queue interface. */
    TimeBuffer<Fetch2Map> *fetch2mapQueue;

    /** Wire to get fetch's output from fetch queue. */
    typename TimeBuffer<Fetch2Map>::wire fromFetch;

    /** Queue of all instructions coming from fetch this cycle. */

    //std::queue<DynInstPtr> insts[Impl::MaxThreads];
    std::queue<BlockPtr> instBlocks[Impl::MaxThreads];

    /** Skid buffer between fetch and map. */
    //std::queue<DynInstPtr> skidBuffer[Impl::MaxThreads];
    std::queue<BlockPtr> skidBuffer[Impl::MaxThreads];

    /** Variable that tracks if map has written to the time buffer this
     * cycle. Used to tell CPU if there is activity this cycle.
     */
    bool wroteToTimeBuffer;

    /** Source of possible stalls. */
    struct Stalls {
        bool execute;
        bool commit;
    };

    /** Tracks which stages are telling map to stall. */
    Stalls stalls[Impl::MaxThreads];

    /** Rename to map delay, in ticks. */
    unsigned executeToMapDelay;

    /** Commit to map delay, in ticks. */
    unsigned commitToMapDelay;

    /** Fetch to map delay, in ticks. */
    unsigned fetchToMapDelay;

    /** The width of map, in instructions. */
    unsigned mapWidth;

    /** Index of instructions being sent to execute. */
    unsigned toExecuteIndex;

    /** number of Active Threads*/
    ThreadID numThreads;

    /** List of active thread ids */
    std::list<ThreadID> *activeThreads;

    /** Maximum size of the skid buffer. */
    unsigned skidBufferMax;

    #if 0
    /** Number of branches in flight. */
    unsigned branchCount[Impl::MaxThreads];

    /** Tells when their is a pending delay slot inst. to send
     *  to rename. If there is, then wait squash after the next
     *  instruction (used for MIPS).
     */
    bool squashAfterDelaySlot[Impl::MaxThreads];

    /** Instruction used for squashing branch (used for MIPS)*/
    DynInstPtr squashInst[Impl::MaxThreads];

    /** SeqNum of Squashing Branch Delay Instruction (used for MIPS)*/
    Addr bdelayDoneSeqNum[Impl::MaxThreads];
    #endif

    /** Stat for total number of idle cycles. */
    Stats::Scalar mapIdleCycles;
    /** Stat for total number of blocked cycles. */
    Stats::Scalar mapBlockedCycles;
    /** Stat for total number of normal running cycles. */
    Stats::Scalar mapRunCycles;
    /** Stat for total number of unblocking cycles. */
    Stats::Scalar mapUnblockCycles;
    /** Stat for total number of squashing cycles. */
    Stats::Scalar mapSquashCycles;
    /** Stat for total number of mapd instructions. */
    Stats::Scalar mapMappedInstBlocks;
    /** Stat for total number of squashed instructions. */
    Stats::Scalar mapSquashedInstBlocks;
};

#endif // __CPU_EDGE_MAP_HH__
